package cn.edu.ntu.controller;

import java.io.IOException;
import java.util.UUID;

import javax.websocket.Session;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.edu.ntu.entity.HttpResult;
import cn.edu.ntu.websocket.WebSocketServer;

@Controller
public class QRController {

	@RequestMapping(value="login", method=RequestMethod.GET)
	public String qrcodeLogin(Model model){
		model.addAttribute("uuid", UUID.randomUUID().toString());
		return "login";
	}
	
	@RequestMapping(value="/login/{uuid}", method=RequestMethod.GET)
	public String login(Model model, @PathVariable String uuid) throws IOException{
		model.addAttribute("uuid", uuid);
		Session session = WebSocketServer.sessionMap.get(uuid);
		if(session != null){
			session.getBasicRemote().sendText("{\"status\":1}");
		}
		return "loginMobile";
	}
	
	@RequestMapping(value="/loginIn/{uuid}", method=RequestMethod.GET)
	@ResponseBody
	public HttpResult loginIn(@PathVariable String uuid) throws IOException{
		Session session = WebSocketServer.sessionMap.get(uuid);
		if(session != null){
			session.getBasicRemote().sendText("{\"status\":2}");
		}
		return HttpResult.ok().build();
	}
	
}
